import _ from 'lodash';
import { WeaLocaleProvider } from "ecCom";
import { comsType } from "../../../../constants/form";
import './index.less';

const getLabel = WeaLocaleProvider.getLabel;
const { FORM_HEADER, FORM_FOOTER } = comsType;

const get = (name, handle = null) => {
  return type => {
    let Com;

    try {
      type = type.replace(/_/g, '-').toLowerCase();
      Com = require(`./${type}/${name}`).default;
    } catch(error) {
      Com = handle;
    }

    return Com;
  }
}
const getValidate = get('validate', {});
const getTransfer = get('transfer');

export const getView = get('View');
export const getProps = get('Props');
export const getDefaultData = get('data', {});

export const getViewableComponent = com => {
  const isInFormBody = ![FORM_HEADER, FORM_FOOTER].includes(com.type);
  const isNotSubComponent = !com.pid;

  return isNotSubComponent && isInFormBody;
};

const propsCfgToViewCfg = (type, propsCfg) => {
  const transfer = getTransfer(type);

  if(!transfer) return propsCfg;

  let viewCfg = propsCfg;

  if(transfer.toViewData) {
    viewCfg = {
      ...propsCfg,
      ...transfer.toViewData(propsCfg),
    };
  }

  return viewCfg;
};

// 组件props配置 转成view配置
export const propsComToViewCom = component => {
  const com = { ...component };
  const defaultRule = { validate: '', error: () => '' };
  const { required, min, max, title, hidden } = com.config;
  const { required: vRequired = defaultRule, limit = defaultRule, custom } = getValidate(com.type);

  com.rules = [];
  com.name = title;
  com.visible = true; // 用于控制组件显隐，如字段显示规则

  if(required == 1) {
    com.rules.push({
      validate: vRequired.validate || (({ value }) => {
        // 兼容String和空数组
        return undefined !== value && !!String(value);
      }),
      error: ({ name }) => `${getLabel('502542','请填写')+name}`
    });
  }

  if (hidden && hidden == 1) { //隐藏字段不做渲染
    com.visible = false;
  }

  if(min && min.value || max && max.value) {
    com.rules.push(limit);
  }

  if(custom) {
    com.rules.push(custom);
  }

  com.config = propsCfgToViewCfg(com.type, com.config);

  if('defaultValue' in com.config) {
    com.value = com.config.defaultValue;
  }

  return com;
}

export { propsCfgToViewCfg };

export const generateSubComponents = com => {
  const type = com.type.toLowerCase();
  const { split } = getTransfer(type);

  return split(com);
}